﻿// (c) Norbert Huffschmid
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.

using System;
using System.Windows.Threading;
using System.Windows;
using System.ComponentModel;

namespace SpinDotters.Core
{
    /// <summary>
    /// Ticker control
    /// </summary>
    public class Ticker : DomainUpDown
    {
        private const int TIMER_DEFAULT_INTERVAL = 2;

        private DispatcherTimer timer = new DispatcherTimer();

        /// <summary>
        /// Timer interval dependency property.
        /// </summary>
        public static readonly DependencyProperty IntervalProperty =
            DependencyProperty.Register(
                "Interval",
                typeof(int),
                typeof(Ticker),
                new PropertyMetadata(TIMER_DEFAULT_INTERVAL, new PropertyChangedCallback(OnIntervalChanged))
            );

        /// <summary>
        /// Gets or sets the ticker interval in seconds.
        /// </summary>
        [Category("SpinDotters")]
        public int Interval
        {
            get { return (int)GetValue(IntervalProperty); }
            set { SetValue(IntervalProperty, value); }
        }

        public Ticker()
        {
            this.ReadOnly = true;

            this.Loaded += new RoutedEventHandler(Ticker_Loaded);
            this.Unloaded += new RoutedEventHandler(Ticker_Unloaded);

            timer.Interval = new TimeSpan(0, 0, TIMER_DEFAULT_INTERVAL);
            timer.Tick += new EventHandler(timer_Tick);
        }

        /// <summary>
        /// Starts the ticker
        /// </summary>
        public void Start()
        {
            this.timer.Start();
        }

        /// <summary>
        /// Stops the ticker
        /// </summary>
        public void Stop()
        {
            this.timer.Stop();
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            if (this.Items.Count > 0)
                this.SpinUp(1);
        }

        private void Ticker_Loaded(object sender, RoutedEventArgs e)
        {
            Start();
        }

        private void Ticker_Unloaded(object sender, RoutedEventArgs e)
        {
            Stop();
        }

        private static void OnIntervalChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        {
            Ticker ticker = dependencyObject as Ticker;

            if ((ticker != null) && ((int)e.NewValue > 0))
            {
                ticker.timer.Interval = new TimeSpan(0, 0, (int)e.NewValue);
            }
        }
    }
}
